package dth.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import dth.entity.Package;

public class PackageDAO {
	private SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
	private Session session=sessionFactory.openSession();
	public java.util.List<Package> getListPackage()
	{
		session.beginTransaction();
		String queryString="select * from package";
		Query query=session.createSQLQuery(queryString).addEntity(Package.class);
		return query.list();
	}
	public java.util.List<Package> getListPackageByUserId(int userId)
	{
		session.beginTransaction();
		String queryString="select p.* from package p,user_package pu,`user` u where p.package_id=pu.fk_package and u.customer_id=pu.fk_user_id and u.customer_id=:cid";
		Query query=session.createSQLQuery(queryString).addEntity(Package.class);
		query.setParameter("cid", userId);
		return query.list();
	}
	public int delete(int id)
	{
		Transaction tx=session.beginTransaction();
		String queryString="delete from package where package_id= :id";
		Query query=session.createSQLQuery(queryString).setParameter("id", id);
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
	
	public int insert(Package pack)
	{
		Transaction tx=session.beginTransaction();
		String queryString="INSERT into package VALUES(0,:name,:price,:des,:fk_admin_id,:date_insert)";
		System.out.println("-----INSERT into package VALUES(0"+pack.getName()+","+pack.getPrice()+","+pack.getDescription()+","+pack.getFkAdminId()+","+pack.getFkAdminId());
		Query query=session.createSQLQuery(queryString);
		query.setParameter("name",pack.getName());
		query.setParameter("price",pack.getPrice());
		query.setParameter("des",pack.getDescription());
		query.setParameter("fk_admin_id",pack.getFkAdminId());
		query.setParameter("date_insert",pack.getDateInsert());
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
	public int update(Package pack)
	{
		Transaction tx=session.beginTransaction();
		String queryString="update package set package_name=:name,package_price=:price,package_description=:des,fk_admin_id=:fk_ad_id,date_insert=:date where package_id=:id";
		Query query=session.createSQLQuery(queryString);
		query.setParameter("name",pack.getName());
		query.setParameter("price",pack.getPrice());
		query.setParameter("des",pack.getDescription());
		query.setParameter("id",pack.getId());
		query.setParameter("fk_ad_id",pack.getFkAdminId());
		query.setParameter("date",pack.getDateInsert());
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
}
